package com.hy.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.hy.Result.ResponseResult;
import com.hy.medicine.MedicineOrder;
import com.hy.medicine.dingdan.dto.OrderCreateDTO;
import com.hy.service.OrderService;
import com.hy.wxConfig.MyWxPayUtil;
import com.hy.wxConfig.WeChatPayQRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 药品订单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/orderMedicine")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private MyWxPayUtil wxPayUtil;

    @Autowired
    private WeChatPayQRCodeUtil qrCodeUtil;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public ResponseResult createOrder(@RequestBody OrderCreateDTO orderCreateDTO) {
        try {
            Long orderId = orderService.createOrder(orderCreateDTO);

            if (orderId != null) {
                // 生成唯一的商户订单号
                String outTradeNo = String.format("%d%d", orderId, System.currentTimeMillis());

                // 构建商品描述
                String body = "医疗订单-" + orderId;

                // 将金额转换为分为单位的字符串
                String totalFee = orderCreateDTO.getActualPayment()
                        .multiply(new BigDecimal("100"))
                        .setScale(0, BigDecimal.ROUND_HALF_UP)
                        .toString();

                // 生成支付二维码
                String qrCode = wxPayUtil.generateQrCode(body, outTradeNo, totalFee);

                // 生成二维码图片
                String qrCodeImage = qrCodeUtil.generateWeChatPayQrCodeBase64(qrCode);

                // 更新订单的支付流水号
                orderService.updateOutTradeNo(orderId, outTradeNo);

                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("orderId", orderId);
                result.put("outTradeNo", outTradeNo);
                result.put("qrCodeImage", qrCodeImage);
                result.put("totalAmount", orderCreateDTO.getActualPayment());

                return ResponseResult.okResult(result);
            } else {
                return ResponseResult.errorResult(400, "商品库存不足");
            }
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ResponseResult.errorResult(500, "创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/pay")
    public ResponseResult payOrder(
            @RequestParam("orderId") Long orderId,
            @RequestParam("paymentType") String paymentType,
            @RequestParam(value = "totalFee", required = false) String totalFee) {
        log.info("支付订单，订单ID: {}, 支付方式: {}", orderId, paymentType);
        try {
            // 验证订单存在且状态正确
            MedicineOrder order = orderService.getOrderById(orderId);
            if (order == null) {
                return ResponseResult.errorResult(404, "订单不存在");
            }

            if (order.getOrderStatus() != 0) {
                return ResponseResult.errorResult(400, "订单状态不正确");
            }

            // 生成唯一的商户订单号
            String outTradeNo = String.format("%d%d", orderId, System.currentTimeMillis());

            // 确保金额正确
            String payAmount = totalFee;
            if (payAmount == null) {
                payAmount = order.getActualPayment()
                        .multiply(new BigDecimal("100"))
                        .setScale(0, BigDecimal.ROUND_HALF_UP)
                        .toString();
            }

            // 生成支付二维码
            String qrCode = wxPayUtil.generateQrCode(
                    "药品订单支付-" + orderId,
                    outTradeNo,
                    payAmount
            );

            // 生成二维码图片
            String qrCodeImage = qrCodeUtil.generateWeChatPayQrCodeBase64(qrCode);

            // 更新订单的支付流水号
            orderService.updateOutTradeNo(orderId, outTradeNo);

            Map<String, Object> result = new HashMap<>();
            result.put("qrCodeImage", qrCodeImage);
            result.put("orderId", orderId);
            result.put("outTradeNo", outTradeNo);

            return ResponseResult.okResult(result);
        } catch (Exception e) {
            log.error("生成支付二维码失败", e);
            return ResponseResult.errorResult(500, "生成支付二维码失败: " + e.getMessage());
        }
    }

    /**
     * 检查支付状态
     */
    @GetMapping("/checkPayStatus")
    public ResponseResult checkPayStatus(@RequestParam("outTradeNo") String outTradeNo) {
        log.info("检查支付状态，商户订单号: {}", outTradeNo);
        try {
            if (outTradeNo == null || outTradeNo.trim().isEmpty()) {
                return ResponseResult.errorResult(400, "缺少必需的参数: outTradeNo");
            }

            String status = orderService.checkPayStatus(outTradeNo);
            return ResponseResult.okResult(status);
        } catch (Exception e) {
            log.error("查询支付状态失败", e);
            return ResponseResult.errorResult(500, "查询支付状态失败: " + e.getMessage());
        }
    }
    /**
     * 获取订单详情
     */
    @GetMapping("/{orderId}")
    public ResponseResult getOrderDetail(@PathVariable("orderId") Long orderId) {
        log.info("获取订单详情，订单ID: {}", orderId);
        try {
            MedicineOrder order = orderService.getOrderById(orderId);
            if (order == null) {
                return ResponseResult.errorResult(404, "订单不存在");
            }
            return ResponseResult.okResult(order);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ResponseResult.errorResult(500, "获取订单详情失败");
        }
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/list")
    public ResponseResult getOrderList(
            @RequestParam("userId") Long userId,
            @RequestParam(value = "status", required = false) Integer status) {
        log.info("获取用户订单列表，用户ID: {}, 状态: {}", userId, status);
        try {
            List<MedicineOrder> orders = orderService.getOrdersWithItemsByUserId(userId, status);
            return ResponseResult.okResult(orders);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return ResponseResult.errorResult(500, "获取订单列表失败");
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    public ResponseResult cancelOrder(
            @RequestParam("orderId") Long orderId,
            @RequestParam("userId") Long userId) {
        log.info("取消订单，订单ID: {}, 用户ID: {}", orderId, userId);
        try {
            boolean result = orderService.cancelOrder(orderId, userId);
            if (!result) {
                return ResponseResult.errorResult(500, "取消订单失败");
            }
            return ResponseResult.okResult(true);
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return ResponseResult.errorResult(500, "取消订单失败");
        }
    }


    /**
     * 更新订单状态
     */
    @PutMapping("/status")
    public ResponseResult updateOrderStatus(
            @RequestParam("orderId") Long orderId,
            @RequestParam("status") Integer status) {
        log.info("更新订单状态，订单ID: {}, 状态: {}", orderId, status);
        try {
            boolean result = orderService.updateOrderStatus(orderId, status);
            if (!result) {
                return ResponseResult.errorResult(500, "更新订单状态失败");
            }
            return ResponseResult.okResult(true);
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return ResponseResult.errorResult(500, "更新订单状态失败");
        }
    }

    /**
     * 处理微信支付回调
     */
    @PostMapping("/notify")
    public String handlePayNotify(HttpServletRequest request) {
        log.info("接收到微信支付回调");
        try {
            // 读取回调数据
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String notifyData = sb.toString();
            log.info("支付回调数据: {}", notifyData);

            // 解析XML数据
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);

            // 使用注入的wxPayUtil实例的API密钥验证签名
            if (!WXPayUtil.isSignatureValid(notifyData, "2ab9071b06b9f739b950ddb41db2690d")) {
                log.error("支付回调签名验证失败");
                return getWxPayResponse(false, "签名校验失败");
            }

            // 处理支付结果
            String returnCode = notifyMap.get("return_code");
            String resultCode = notifyMap.get("result_code");
            String outTradeNo = notifyMap.get("out_trade_no");

            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                // 更新订单状态
                Long orderId = Long.parseLong(outTradeNo);
                orderService.updateOrderStatus(orderId, 1);  // 1表示已支付
                log.info("订单支付成功并更新状态, 订单号: {}", orderId);
                return getWxPayResponse(true, "支付成功");
            } else {
                log.error("支付失败, 订单号: {}, 错误信息: {}", outTradeNo, notifyMap.get("err_code_des"));
                return getWxPayResponse(false, "支付失败");
            }

        } catch (Exception e) {
            log.error("处理支付回调异常", e);
            return getWxPayResponse(false, "处理失败");
        }
    }

    private String getWxPayResponse(boolean success, String message) {
        Map<String, String> response = new HashMap<>();
        response.put("return_code", success ? "SUCCESS" : "FAIL");
        response.put("return_msg", message);
        try {
            return WXPayUtil.mapToXml(response);
        } catch (Exception e) {
            log.error("生成响应XML失败", e);
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>";
        }
    }

    /**
     * 获取订单详情（使用查询参数）
     */
    @GetMapping("/detail")
    public ResponseResult getOrderDetailByQuery(@RequestParam("orderId") String orderId) {
        log.info("获取订单详情，订单ID: {}", orderId);
        try {
            Long orderIdLong = Long.parseLong(orderId);
            MedicineOrder order = orderService.getOrderById(orderIdLong);
            if (order == null) {
                return ResponseResult.errorResult(404, "订单不存在");
            }
            return ResponseResult.okResult(order);
        } catch (NumberFormatException e) {
            return ResponseResult.errorResult(400, "订单ID格式不正确");
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ResponseResult.errorResult(500, "获取订单详情失败");
        }
    }


}
